
import{Config} from '../utils/config.js';
import { Token } from '../utils/token.js';

class Base{
  constructor(){
    this.baseRequestUrl = Config.restUrl;
  }
  //norefetche为true就不重发
  request(params,norefetch){
    var url = this.baseRequestUrl + params.url
    var that = this;
    if(!params.type){
      params.type ='GET'
    }
    wx.request({
      url: url,
      data: params.data,
      header: {
        'Content-Type': 'application/json',
        'token' : wx.getStorageSync('token')
      },
      method: params.type,
      success: function(res) {
        var code = res.statusCode.toString();
        var startChar = code.charAt(0);

        if(startChar == '2'){
          params.sCallback && params.sCallback(res.data);
        }else{
            if(code == '401'){
              if (!norefetch){
                that._refetch(params);
              }
            }
          if (norefetch){
            params.eCallback && params.eCallback(res.data);
          }
        }
      },
      fail: function(err) {
        console.log(err);
      },
    })
  }

  _refetch(params){
    var token = new Token();
    token.getTokenFromServer((token)=>{
      this.request(params, true);
    })
  }

  getDataSet(event, key){
    return event.currentTarget.dataset[key];
  }

}
export{Base};